'use client'

import { ReactNode, createContext, useContext } from 'react'
import { message as antdMessage } from 'antd'

type MessageApi = ReturnType<typeof antdMessage.useMessage>[0] // 提取 messageApi 类型

const MessageContext = createContext<MessageApi | null>(null)

export const useGlobalMessage = (): MessageApi => {
  const ctx = useContext(MessageContext)
  if (!ctx) throw new Error('useGlobalMessage must be used within GlobalMessageProvider')
  return ctx
}

interface Props {
  children: ReactNode
}

export default function GlobalMessageProvider({ children }: Props) {
  const [messageApi, contextHolder] = antdMessage.useMessage()

  return (
    <MessageContext.Provider value={messageApi}>
      {contextHolder}
      {children}
    </MessageContext.Provider>
  )
}
